#include "logictalk.h"
#include"networkmanager.h"
#include"messageconst.h"

DEFINE_SINGLE_ATTRIBUTES(LogicTalk);

LogicTalk::LogicTalk()
{
    NET_INSTANCE()->add(MESSAGE_WORLD_TALK,handler(this,SEL_EVENTFUNC(LogicTalk::c2sWorldTalk)));
    NET_INSTANCE()->add(MESSAGE_PRIVATE_TALK,handler(this,SEL_EVENTFUNC(LogicTalk::c2sPrivateTalk)));
}

void LogicTalk::c2sWorldTalk(Json::Value& msg)
{
    cout<<"LogicTalk::c2sWorldTalk"<<msg.toStyledString()<<endl;
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps= NET_SOCKET().m_playermaps;
    cout<<playermaps[fd].rolename<<" in the world say: "<<msg["msg"].asString()<<endl;
    msg["fd"]=fd;
    for(auto var:playermaps)
    {
        if(var.first==fd)
            msg["fd"]=-1;
        NET_INSTANCE()->send(var.first,MESSAGE_WORLD_TALK,msg);
            //write(var.first,(char*)msg,sizeof(WorldTalk_Msg));
    }
}

void LogicTalk::c2sPrivateTalk(Json::Value& msg)
{
    int fd=NET_INSTANCE()->getFd();
    auto& playermaps= NET_SOCKET().m_playermaps;
    int dest=msg["dest"].asInt();
    if(playermaps.find(dest)!=playermaps.end())
    {
        msg["fd"]=fd;
        cout<<playermaps[fd].rolename<<" say "<<msg["msg"].asString()<<" to "<<playermaps[dest].rolename<<endl;
        NET_INSTANCE()->send(dest,MESSAGE_PRIVATE_TALK,msg);
        //write(msg->dest,(char*)msg,sizeof(PrivateTalk_Msg));
    }
    msg["fd"]=-1;
    NET_INSTANCE()->send(fd,MESSAGE_PRIVATE_TALK,msg);
}
